import { defineStore } from 'pinia'
import { getUserInfo,getAllUserInfo,changeUserBaseInfo } from '@/api/userHttp'
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {
      id: '',
      openid: '',
      token: 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NDU1Nzc0MTIsInVzZXJJZCI6Mn0.BXG3RJP_pztMI9TwjO7wINoL3uSbPbkysIlMH6Uyc4Y'
    },
    userNextInfo:{},
    isLogin: false
  }),
  
  getters: {
    // 获取用户名
    getUserToken(){
      return this.userInfo.token
    },

    getUsername: (state) => state.userInfo.nickName || '未设置昵称'
  },
  
  actions: {
    // 获取用户信息
    async fetchUserInfo(code) {
      console.log(code);
      // return
      const {data:{data}} = await getUserInfo(code)
      this.userInfo = data
      this.getAllUserInfo(data.token)
      uni.setStorageSync('userInfo', this.userInfo)
      this.isLogin = true
      uni.setStorageSync('isLogin', this.isLogin)
    },

    // 更新用户信息
    // async updateUserInfo(updateData) {
    //   try {
    //     await updateUserInfoApi(updateData)
    //     this.userInfo = { ...this.userInfo, ...updateData }
    //     uni.setStorageSync('userInfo', this.userInfo)
    //     return true
    //   } catch (error) {
    //     console.error('更新用户信息失败:', error)
    //     throw error
    //   }
    // },
    async getAllUserInfo(token){
      const {data:{data}} = await getAllUserInfo(token)
      this.userNextInfo = data
      console.log(this.userNextInfo);
    },
    // 解密手机号
    async decryptPhone(code) {
      try {
        const { data } = await decryptPhoneNumber(code)
        return data.phoneNumber
      } catch (error) {
        console.error('解密手机号失败:', error)
        throw error
      }
    },

    // 退出登录
    logout() {
      this.userInfo = {
        id: '',
        openid: '',
        token: '',
        avatarUrl: '',
        nickName: '',
        phone: ''
      }
      this.isLogin = false
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('isLogin')
    },
    
    async changeUserBaseInfo(){
      await changeUserBaseInfo(this.userNextInfo,this.userInfo.token)
    }
    
  }
}) 